<template>
  <div>
    <div class="search">
      <div class="search-input" @click="gotoSearch">
        <img class="icon" src="/static/icon/search.svg" alt="" />
        <div class="name">
          {{ options.query || '搜索点位名称' }}
        </div>
      </div>
    </div>
    <div class="filter">
      <div
        :class="['filter-item', { active: handleFilterItemActive('service') }]"
        @click="openFilter('service')"
      >
        <div class="name">服务站点</div>
        <img class="arrow" src="/static/icon/down-arrow.svg" alt="" />
        <img class="arrow-green" src="/static/icon/down-arrow-green.svg" alt="" />
      </div>
      <div
        :class="['filter-item', { active: handleFilterItemActive('public') }]"
        @click="openFilter('public')"
      >
        <div class="name">公共资源</div>
        <img class="arrow" src="/static/icon/down-arrow.svg" alt="" />
        <img class="arrow-green" src="/static/icon/down-arrow-green.svg" alt="" />
      </div>
      <div class="filter-box" v-show="showFilter">
        <div class="header">
          <div class="title">点位筛选</div>
          <div class="clean" @click="clearHistoryFilter">
            <img class="icon" src="/static/icon/clean.svg" alt="" />
            清除
          </div>
        </div>
        <div class="body">
          <div
            :class="['item', { active: handleFilterItemActive('item', item.id) }]"
            v-for="item in showFilterList"
            :key="item.id"
            @click="handleFilterItemClick(item.id)"
          >
            <div>{{ item.name }}</div>
          </div>
        </div>
      </div>
    </div>
    <map
      id="map"
      ref="map"
      @poitap="handlePoitap"
      @markertap="handleMarkertap"
      @callouttap="handleMarkertap"
      :markers="filterSpotList"
      :longitude="position.longitude"
      :latitude="position.latitude"
      :scale="scale"
    >
    </map>
    <div class="tools">
      <div class="item">
        <div class="add" @click="handleMapScale('add')"></div>
        <div class="sub" @click="handleMapScale('sub')"></div>
      </div>
      <div class="item location" @click="getCurrentLocation">
        <img class="icon" src="/static/icon/location.svg" alt="" />
      </div>
    </div>
    <div class="service-button" @click="gotoService">
      <img class="icon" src="/static/icon/service.svg" alt="" />
      <img class="arrow" src="/static/icon/right-arrow.svg" alt="" />
    </div>
    <div class="mask" v-show="showSpotDialog" @click="showSpotDialog = false"></div>
    <div class="marker-detail" v-show="showSpotDialog">
      <div class="header">
        <div class="name">{{ clickMarker.name }}</div>
        <div class="close" @click="showSpotDialog = false"></div>
      </div>
      <div class="tag">
        {{ clickMarker.category }}
      </div>
      <div class="content-list">
        <div class="item" v-if="clickMarker.content">
          <div class="name">简介:</div>
          <div class="content">{{ clickMarker.content }}</div>
        </div>
        <div class="item" v-if="clickMarker.address">
          <div class="name">地址:</div>
          <div class="content">{{ clickMarker.address }}</div>
        </div>
        <div class="item" v-if="clickMarker.trainingInstitution">
          <div class="name">培训机构:</div>
          <div class="content">{{ clickMarker.trainingInstitution }}</div>
        </div>
        <div class="item" v-if="clickMarker.trainingType">
          <div class="name">培训工种:</div>
          <div class="content">{{ clickMarker.trainingType }}</div>
        </div>
        <div class="item" v-if="clickMarker.talentManager">
          <div class="name">培训工种:</div>
          <div class="content">{{ clickMarker.talentManager }}</div>
        </div>
        <div class="list">
          <div class="item" v-if="clickMarker.contact">
            <div class="name">联系人:</div>
            <div class="content">{{ clickMarker.contact }}</div>
          </div>
          <div class="item" v-if="clickMarker.contactPerson">
            <div class="name">联系人:</div>
            <div class="content">{{ clickMarker.contactPerson }}</div>
          </div>
        </div>
        <div class="item jump-link" v-if="clickMarker.link">
          <div>
            <div class="name">跳转链接:</div>
            <div class="content">{{ clickMarker.link }}</div>
          </div>
          <div class="copy" @click="copyLink">
            <div class="text">复制链接</div>
          </div>
        </div>
      </div>
      <div
        class="button"
        @click="handleSpotClick(clickMarker.serviceIdList[0])"
        v-if="clickMarker?.serviceIdList?.length > 0"
      >
        <img class="icon" src="/static/icon/service.svg" alt="" />
        办理业务
      </div>
    </div>
  </div>
</template>

<script setup>
wx.showShareMenu({
  withShareTicket: true,
  menus: ['shareAppMessage', 'shareTimeline'],
})
import { computed, onMounted, ref, watch } from 'vue'
import { onLoad, onReady } from '@dcloudio/uni-app'
import { getFilterList, getSpotList } from '/api/data.js'
import { getCurrentInstance } from 'vue'
const { ctx } = getCurrentInstance()
const showFilter = ref(false)
const showSpotDialog = ref(false)
const historyFilter = ref({
  serviceList: [],
  publicList: [],
  query: '',
}) // 用于存储历史筛选记录
const filterType = ref('') // 用于标记当前筛选的类型
const filterList = ref([])
const filterSpotList = ref([]) // 用于存储筛选后的点位列表
watch(
  () => historyFilter.value,
  (newVal) => {
    // 监听历史筛选记录的变化
    const serviceArray = newVal.serviceList || []
    const publicArray = newVal.publicList || []
    const categoryArray = [...serviceArray, ...publicArray]
    // 如果没有任何筛选条件，则显示所有点位
    filterSpotList.value = spotList.value
    if (categoryArray.length == 0 && !newVal.query) {
      return
    }
    if (newVal.query) {
      filterSpotList.value = filterSpotList.value.filter((item) => {
        // 点位名称
        if (item.name.includes(newVal.query)) {
          return true
        }
        return false
      })
    }
    if (categoryArray.length > 0) {
      filterSpotList.value = filterSpotList.value.filter((item) => {
        // 如果选中了服务站点、公共资源，则返回对应类别的点位
        if (categoryArray.includes(item.categoryId)) {
          return true
        }
        return false
      })
    }
    filterSpotList.value = filterSpotList.value.map((item) => {
      return {
        id: item.id,
        iconPath: handleProxy(item.icon),
        latitude: item.lat,
        longitude: item.lng,
        width: 33,
        height: 33,
        callout: {
          content: item.name,
          fontSize: 12,
          color: '#FFFFFF', //文本颜色
          borderRadius: 14, //边框圆角
          borderWidth: 1.5, //边框宽度
          borderColor: '#FFFFFF', //边框颜色
          bgColor: '#13B7A4', //背景色
          padding: 5, //文本边缘留白
          textAlign: 'center', //文本对齐方式。有效值: left, right, center
          display: 'ALWAYS',
        },
      }
    })
  },
  { deep: true }
)
const showFilterList = computed(() => {
  if (filterType.value == 'service') {
    return filterList.value['serviceList'] || []
  } else if (filterType.value == 'public') {
    return filterList.value['publicList'] || []
  }
  return []
})
const handleFilterItemClick = (id) => {
  // 处理筛选项点击事件
  if (historyFilter.value[filterType.value + 'List']?.includes(id)) {
    // 如果已经存在，则移除该筛选项
    const index = historyFilter.value[filterType.value + 'List']?.indexOf(id)
    if (index > -1) {
      historyFilter.value[filterType.value + 'List']?.splice(index, 1)
    }
    return
  }
  historyFilter.value[filterType.value + 'List']?.push(id)
}
const handleFilterItemActive = (type, id) => {
  if (type == 'item') return historyFilter.value[filterType.value + 'List']?.includes(id)
  // 判断筛选项是否被选中
  return historyFilter.value[type + 'List']?.length != 0
}
const clearHistoryFilter = () => {
  // 清除历史筛选记录
  historyFilter.value[filterType.value + 'List'] = []
}
const position = ref({
  longitude: 121.42368827343921,
  latitude: 28.650000824581394,
})
let map = null
const scale = ref(12)
const openFilter = (type) => {
  showFilter.value = !showFilter.value
  filterType.value = type
}
const gotoService = () => {
  uni.redirectTo({
    url: '/pages/service/service',
  })
}
const gotoSearch = () => {
  const url = '/pages/source-search/source-search'
  if (options.value.query) {
    uni.redirectTo({ url })
  } else {
    uni.navigateTo({ url })
  }
}
const getCurrentLocation = () => {
  uni.getLocation({
    type: 'gcj02',
    timeout: '1000',
    success: function (res) {
      position.value.longitude = res.longitude
      position.value.latitude = res.latitude
    },
    fail: (err) => {
      uni.hideLoading()
      uni.showModal({
        title: '提示',
        content: '获取位置失败，请授权定位权限',
        cancelText: '不授权',
        confirmText: '授权',
        success: function (res) {
          if (res.confirm) {
            uni.authorize({
              scope: 'scope.userLocation',
              success: function () {
                getCurrentLocation()
              },
              fail: function () {
                wx.openSetting()
                uni.showToast({
                  title: '授权失败',
                  icon: 'none',
                })
              },
            })
          }
        },
      })
    },
  })
}
const handlePoitap = (e) => {
  showFilter.value = false
}
const clickMarkerId = ref(-1)
const clickMarker = computed(() => {
  if (clickMarkerId.value == -1) return {}
  return spotList.value.find((item) => item.id == clickMarkerId.value) || {}
})
const handleSpotClick = (id) => {
  showSpotDialog.value = false
  uni.navigateTo({
    url: `/pages/service/service?serviceId=${id}`,
  })
}
const copyLink = () => {
  uni.setClipboardData({
    data: clickMarker.value.link,
    success: () => {
      uni.showToast({
        title: '链接已复制',
        icon: 'success',
      })
    },
    fail: () => {
      uni.showToast({
        title: '复制失败',
        icon: 'none',
      })
    },
  })
}
const handleMarkertap = (e) => {
  if (showSpotDialog.value) return
  clickMarkerId.value = e.detail.markerId
  showSpotDialog.value = true
}
import { handleProxy } from '/api/data.js'
const handleMapScale = (type) => {
  map.getScale({
    success: (res) => {
      let data = res.scale
      map.getCenterLocation({
        success: (res) => {
          position.value.latitude = res.latitude
          position.value.longitude = res.longitude
          if (type == 'add') {
            scale.value = data + 1
          } else if (type == 'sub') {
            scale.value = data - 1
          }
        },
      })
    },
  })
}
const spotList = ref([])
const options = ref({})
onMounted(() => {
  map = uni.createMapContext('map', ctx)
  getSpotList().then((res) => {
    spotList.value = res.data.data || []
    const query = options.value.query || ''
    historyFilter.value = {
      serviceList: options.value.categoryId ? [Number(options.value.categoryId)] : [],
      publicList: [],
      query,
    }
  })
  getFilterList().then((res) => {
    filterList.value = res.data.data || []
  })
})
onLoad((e) => {
  if (e) {
    options.value = e
  }
})
</script>

<style lang="scss">
.jump-link {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  gap: 12rpx;
}
.list {
  display: grid;
  grid-template-columns: 1fr 1fr;
}
.copy {
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  background: linear-gradient(270deg, #44d4a8 0%, #30d1e6 100%);
  height: 50rpx;
  padding: 0 10rpx;
  .text {
    font-family: PingFang SC;
    font-weight: 500;
    font-style: Medium;
    font-size: 28rpx;
    color: #fff;
  }
}
.mask {
  position: fixed;
  top: 176rpx;
  left: 0;
  width: 100vw;
  height: calc(100vh - 176rpx);
  background: #00000055;
}
.marker-detail {
  position: fixed;
  width: 560rpx;
  min-height: 108rpx;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 16rpx;
  background-color: #fff;
  z-index: 11;
  padding: 32rpx;

  .header {
    position: relative;
    display: flex;
    justify-content: space-between;
    height: 76rpx;

    &::before {
      position: absolute;
      content: '';
      width: 560rpx;
      bottom: 0;
      left: -32rpx;
      height: 2rpx;
      background: #0000000d;
    }

    .name {
      font-family: PingFang SC;
      font-weight: 500;
      font-style: Medium;
      font-size: 30rpx;
      color: #333333;
    }

    .close {
      margin-top: 4rpx;
      position: relative;
      width: 30rpx;
      height: 30rpx;

      &::after {
        position: absolute;
        left: 50%;
        width: 4rpx;
        height: 100%;
        margin-left: -1rpx;
        content: '';
        background: #94979c;
        rotate: -45deg;
      }

      &::before {
        position: absolute;
        left: 50%;
        width: 4rpx;
        height: 100%;
        margin-left: -1rpx;
        content: '';
        background: #94979c;
        rotate: 45deg;
      }
    }
  }

  .tag {
    margin-top: 32rpx;
    width: fit-content;
    height: 46rpx;
    border-radius: 8rpx;
    text-align: center;
    padding: 8rpx 16rpx;
    background-color: #38d3c31a;
    font-family: PingFang SC;
    font-weight: 500;
    font-style: Medium;
    font-size: 22rpx;
    color: #13b7a4;
  }

  .content-list {
    max-height: 550rpx;
    overflow: scroll;
  }

  .item {
    margin-top: 32rpx;

    .name {
      font-family: PingFang SC;
      font-weight: 400;
      font-style: Regular;
      font-size: 24rpx;
      color: #94979c;
    }

    .content {
      margin-top: 8rpx;
      font-family: PingFang SC;
      font-weight: 400;
      font-style: Regular;
      font-size: 28rpx;
      color: #333333;
      word-break: break-all;
      word-wrap: break-word;
      white-space: pre-wrap;
    }
  }

  .button {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8rpx;
    margin-top: 32rpx;
    width: 100%;
    height: 80rpx;
    border-radius: 12rpx;
    color: #ffffff;
    background: linear-gradient(270deg, #44d4a8 0%, #30d1e6 100%);

    .icon {
      width: 32rpx;
      height: 32rpx;
    }
  }
}

.service-button {
  position: fixed;
  right: 0rpx;
  top: 70%;
  transform: translateY(-50%);
  width: 104rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  border-top-width: 4rpx;
  border-bottom-width: 4rpx;
  border-left-width: 4rpx;
  border-top-left-radius: 24rpx;
  border-bottom-left-radius: 24rpx;
  background: linear-gradient(270deg, #44d4a8 0%, #30d1e6 100%);
  box-shadow: 0rpx 8rpx 16rpx 0rpx #38d3c340;

  .icon {
    width: 48rpx;
    height: 48rpx;
    flex-shrink: 0;
  }

  .arrow {
    height: 20rpx;
    width: 20rpx;
  }
}

.tools {
  position: fixed;
  right: 24rpx;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  gap: 16rpx;

  .item {
    border-radius: 16rpx;
    background: #fff;

    .icon {
      margin: 20rpx;
      width: 40rpx;
      height: 40rpx;
    }
  }

  .add,
  .sub {
    position: relative;

    &::after {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      content: '';
      width: 32rpx;
      height: 4rpx;
      background: #13b7a4;
    }
  }

  .add {
    &::before {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      content: '';
      width: 4rpx;
      height: 32rpx;
      background: #13b7a4;
    }
  }

  .sub {
    &::before {
      position: absolute;
      left: 50%;
      top: 0;
      transform: translateX(-50%);
      content: '';
      height: 2rpx;
      width: 64rpx;
      background: #0000000d;
    }
  }

  .location,
  .add,
  .sub {
    width: 80rpx;
    height: 80rpx;
  }
}

#map {
  width: 750rpx;
  height: calc(100vh - 176rpx);
}

.filter {
  position: relative;
  width: 750rpx;
  height: 88rpx;
  display: flex;

  .filter-item {
    flex: 1;
    flex-shrink: 0;
    height: 88rpx;
    color: #646566;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 8rpx;

    .name {
      font-family: PingFang SC;
      font-weight: 400;
      font-style: Regular;
      font-size: 28rpx;
      letter-spacing: 0rpx;
    }

    .arrow,
    .arrow-green {
      width: 16rpx;
      height: 16rpx;
      margin-top: 4rpx;
    }

    .arrow-green {
      display: none;
    }
    &.active {
      color: #13b7a4;
      .arrow {
        display: none;
      }
      .arrow-green {
        display: block;
      }
    }
  }
}

.search {
  width: 750rpx;
  height: 88rpx;
  padding: 8rpx 24rpx;

  .search-input {
    width: 702rpx;
    height: 72rpx;
    border-radius: 44rpx;
    background: #f7f8fa;
    display: flex;
    align-items: center;
    gap: 20rpx;
    padding: 16rpx 24rpx;

    .icon {
      width: 40rpx;
      height: 40rpx;
    }

    .name {
      font-family: PingFang SC;
      font-weight: 400;
      font-style: Regular;
      font-size: 28rpx;
      color: #c8c9cc;
    }
  }
}
</style>
